package database

import (
	"chi-med-det-server-go/models"
	"fmt"
	"strings"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

const (
	DNS = "test:test@1234@tcp(8.134.212.211:3306)/chi_med_det?charset=utf8mb4&parseTime=True&loc=Local"
)

type DBUtil struct {
	db *gorm.DB
}

func (dbUtil *DBUtil) InitDataBase() {
	var err error
	dbUtil.db, err = gorm.Open(mysql.Open(DNS), &gorm.Config{})
	if dbUtil.db != nil && err == nil {
		fmt.Printf("InitDataBase(), Open DB Successfully。\n")
	} else {
		fmt.Printf("InitDataBase(), Open DB error。 error message=%s\n", err.Error())
	}
}

func (dbUtil *DBUtil) InsertUser(user models.User) bool {
	if dbUtil.db != nil {
		if dbUtil.QueryUserByAccount(user.Account) != nil {
			return false
		}
		result := dbUtil.db.Create(&user)
		if result.Error == nil {
			fmt.Println("InsertUser(), InsertUser DB Successfully")
			return true
		} else {
			fmt.Println("InsertUser(), Failed to InsertUser to DB")
			return false
		}
	}
	return false
}

func (dbUtil *DBUtil) QueryUserByAccount(account string) *models.User {
	var user models.User
	dbUtil.db.Where("account = ?", account).Find(&user)
	fmt.Printf("QueryUserByAccount(), user.Account=%s, userPassword=%s\n", user.Account, user.Password)
	if len(strings.TrimSpace(user.Account)) == 0 ||
		len(strings.TrimSpace(user.Password)) == 0 {
		return nil
	}
	return &user
}

func (dbUtil *DBUtil) InsertFeedback(feedback models.Feedback) bool {
	if dbUtil.db != nil {
		result := dbUtil.db.Create(&feedback)
		if result.Error == nil {
			fmt.Println("InsertFeedback(), InsertUser DB Successfully")
			return true
		} else {
			fmt.Println("InsertFeedback(), Failed to InsertFeedback to DB")
			return false
		}
	}
	return false
}
